# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def distributeCoins(self, root: TreeNode) -> int:
        def distribute(root):
            if root.left is None and root.right is None:
                return root.val - 1
            left_move = distribute(root.left) if root.left else 0
            right_move = distribute(root.right) if root.right else 0

            if root.left:
                root.val += (root.left.val - 1)
            if root.right:
                root.val += (root.right.val - 1)

            return abs(left_move) + abs(right_move) + abs(root.val - 1)

        return distribute(root)
